package com.exam.service.impl;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.exam.exception.BaseException;
import com.exam.pojo.User;
import com.exam.mapper.UserMapper;
import com.exam.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exam.util.ExcelListener;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XiaoKai
 * @since 2021-07-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    public User login(String account,String password){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", account);
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1==null){
            throw new BaseException("用户名不存在！");
        }
        queryWrapper.select("id","account","name","sex","tel","email","major","create_time","update_time","active","ranked");
        queryWrapper.eq("password",password);
        User user = userMapper.selectOne(queryWrapper);
        if(user==null){
            throw new BaseException("用户名密码错误");
        }
        return user;
    }

    /**
     * 导入用户
     * @param file
     * @throws IOException
     */
    public boolean excelImportStu(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //实例化实现了AnalysisEventListener接口的类
        ExcelListener listener = new ExcelListener();
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
        //读取信息
        excelReader.read(new Sheet(1, 1, User.class));
        //获取数据
        List<Object> list = listener.getDatas();
        List<User> originalList = new ArrayList<User>();
        User catagory = new User();
        //转换数据类型
        for (int i = 0; i < list.size(); i++) {
            catagory = (User) list.get(i);
            originalList.add(catagory);
        }
        //对list进行去重并拿到新的list
        List<User> lists = originalList.stream()
                .filter(u -> StringUtils.isNotBlank(u.getTel()))
                .collect(Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<User>(Comparator.comparing(User::getTel))), ArrayList::new));
        //执行批量插入
        if (lists.size() > 0) {
            userMapper.addLists(lists);
            return true;
        }
        return false;
    }
}
